package com.pangu.web.handler.api.agentuser;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.pangu.core.BMDataContext;
import com.pangu.core.cache.CacheConfigTools;
import com.pangu.core.cache.CacheHelper;
import com.pangu.util.BeiMiDic;
import com.pangu.util.GameUtils;
import com.pangu.util.IP;
import com.pangu.util.IPTools;
import com.pangu.util.RSATool;
import com.pangu.util.UKTools;
import com.pangu.util.disruptor.DisruptorHandler;
import com.pangu.util.rules.model.RespCode;
import com.pangu.util.rules.model.RespEntity;
import com.pangu.web.handler.service.SsoCenterService;
import com.pangu.web.model.AgentInfo;
import com.pangu.web.model.PlayUser;
import com.pangu.web.model.PlayUserClient;
import com.pangu.web.model.SsoRequestInfo;
import com.pangu.web.model.SysDic;
import com.pangu.web.model.SysGameConfig;
import com.pangu.web.model.Token;
import com.pangu.web.service.repository.es.PlayUserClientESRepository;
import com.pangu.web.service.repository.es.PlayUserESRepository;
import com.pangu.web.service.repository.es.SsoRequestInfoESRepository;
import com.pangu.web.service.repository.es.TokenESRepository;
import com.pangu.web.service.repository.jpa.PlayUserRepository;

/**
* @ClassName: SsoLoginController 
* @Description: 代理商用户相关操作
* @date 2018年3月30日 下午8:58:45 
*
 */
@RestController
@RequestMapping("/api/sso")
@CrossOrigin
public class SsoCenterController{
	@Autowired
	private TokenESRepository tokenESRes ;
	@Autowired
	private PlayUserClientESRepository playUserClientRes ;
	@Autowired
	private PlayUserESRepository playUserESRes;
	@Autowired
	private SsoRequestInfoESRepository SsoReqInfoESRes;
	@Autowired
	private PlayUserRepository playUserRes ;
	@Autowired
	private SsoCenterService ssoCenterService ;
	
	
	/**
	* @Description: 
	* 代理商用户注册接口
	* 1、如果用户已经注册，则直接返回登录token
	* 2、用户首次注册，系统保存账户信息，返回token
	* @param  request
	* @param  reqobj 
	* @return RespEntity  
	* @date 2018年4月16日 下午1:00:49   
	 */
	@PostMapping("/register")
    public RespEntity register(HttpServletRequest request,@RequestBody JSONObject reqobj) {
		//判断代理机构是否存在
		AgentInfo aginfo=ssoCenterService.judgementAgentExist(reqobj.getString("agent"));
		if(aginfo==null){
			return new RespEntity(RespCode.R1001);
		}
		//解密参数
		JSONObject jsonobj=null;
		try {
			jsonobj=ssoCenterService.decryptAgentRegisterData(aginfo,reqobj.getString("data"));
			if(jsonobj==null) {
				return new RespEntity(RespCode.R1002);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new RespEntity(RespCode.R1003);
		}
		/*SsoRequestInfo ssoRequestInfo=SsoReqInfoESRes.findByOrderidAndOrderidtype(jsonobj.getString("orderid"), Content.OrderIdType.REGISTER.toString());
		if(ssoRequestInfo!=null) {
			return new RespEntity(RespCode.R1009);
		}else {
			ssoRequestInfo=new SsoRequestInfo();
			ssoRequestInfo.setOrderid(jsonobj.getString("orderid"));
			ssoRequestInfo.setOrderidtype(Content.OrderIdType.REGISTER.toString());
		}*/
		//校验md5签名
		if(!reqobj.getString("key").equals(RSATool.getMD5(reqobj.getString("agent")+reqobj.getString("timestamp")))) {
			return new RespEntity(RespCode.R1004);
		};
		////判断用户是否存在，不存在则创建,并初始化用户的余额
		String ip = UKTools.getIpAddr(request);
		IP ipdata = IPTools.getInstance().findGeography(ip);
		PlayUserClient playUserClient = playUserClientRes.findByUsername(jsonobj.getString("account"));
		if(playUserClient == null){//ES中如果没有该对象
			try {
				PlayUser playuser=playUserRes.findByUsername(jsonobj.getString("account"));
				playUserClient=new PlayUserClient();
				if(playuser==null) {
					playuser=new PlayUser();
					playuser = GameUtils.createAgentPlayUser(playuser, ipdata, request,BMDataContext.PlayerTypeEnum.NORMAL.toString());
					playuser.setAgentcode(reqobj.getString("agent"));
					playuser.setUsername(jsonobj.getString("account"));
					playuser.setGoldcoins(Double.valueOf(jsonobj.getString("money")));
					BeanUtils.copyProperties(playUserClient , playuser);
					DisruptorHandler.published(playuser , playUserESRes , playUserRes);
					ssoCenterService.updateAgentCoins(aginfo, Double.valueOf(jsonobj.getString("money")), 0);
					ssoCenterService.saveTransferLog(request, playUserClient.getId(),  playUserClient.getUsername(),0,Double.valueOf(jsonobj.getString("money")));//保存上下分日志
				}else {
					BeanUtils.copyProperties(playUserClient, playuser);
					playUserClientRes.save(playUserClient);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return new RespEntity(RespCode.R9999);
			}
		}
		Token userToken= new Token();
		userToken.setId(UKTools.getUUID());
		userToken.setIp(ip);
		userToken.setRegion(ipdata.getProvince()+ipdata.getCity());
		userToken.setUserid(playUserClient.getId());
		userToken.setCreatetime(new Date());
		userToken.setOrgi(playUserClient.getOrgi());
		SysGameConfig config = CacheConfigTools.getSysGameConfig(BMDataContext.SYSTEM_ORGI) ;
		if(config!=null && config.getLoginexpdays()>0){
			userToken.setExptime(new Date(System.currentTimeMillis()+60*60*24*config.getLoginexpdays()*1000));//默认有效期 ， 7天
		}else{
			//设置过期时间
			userToken.setExptime(new Date(System.currentTimeMillis()+60*60*24*7*1000));//默认有效期 ， 7天
		}
		userToken.setLastlogintime(new Date());
		userToken.setUpdatetime(new Date(0));
		//保存token到
		tokenESRes.save(userToken) ;
		//保存此次请求orderid
		//SsoReqInfoESRes.save(ssoRequestInfo);
		CacheHelper.getApiUserCacheBean().put(userToken.getId(),userToken, userToken.getOrgi());
		CacheHelper.getApiUserCacheBean().put(playUserClient.getId(),playUserClient, userToken.getOrgi());
		
		JSONObject resobj=new JSONObject();
		List<SysDic> sysdiclist=BeiMiDic.getInstance().getDic(BMDataContext.BEIMI_SYSTEM_GAME_CLIENTADDR);
		for(SysDic sysdic:sysdiclist){
			if(sysdic.getCode().equals(playUserClient.getOstype())) {
				resobj.put("url", sysdic.getDescription()+"?token="+userToken.getId());
				resobj.put("token", userToken.getId());
				break;
			}
		}
		if(resobj.isEmpty()) {
			SysDic sysdic=sysdiclist.get(0);
			resobj.put("url", sysdic.getDescription()+"?token="+userToken.getId());
			resobj.put("token", userToken.getId());
		}
		return new RespEntity(RespCode.R0000,resobj);
	}
	
	//上分下方接口（网站端发起）
	@PostMapping("/balanceTransfer")
    public RespEntity balanceTransfer(HttpServletRequest request,@RequestBody JSONObject reqobj) {
		//判断代理机构是否存在
		AgentInfo aginfo=ssoCenterService.judgementAgentExist(reqobj.getString("agent"));
		if(aginfo==null){
			return new RespEntity(RespCode.R1001);
		}
		//解密转账参数
		JSONObject datajsonobj=null;
		try {
			datajsonobj=ssoCenterService.decryptAgentTransferData(aginfo,reqobj.getString("data"));
			if(datajsonobj==null) {
				return new RespEntity(RespCode.R1002);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new RespEntity(RespCode.R1003);
		}
		SsoRequestInfo ssoRequestInfo=SsoReqInfoESRes.findByOrderidAndOrderidtype(datajsonobj.getString("orderid"), BMDataContext.OrderIdType.TRANSTER.toString());
		if(ssoRequestInfo!=null) {
			return new RespEntity(RespCode.R1009);
		}else {
			ssoRequestInfo=new SsoRequestInfo();
			ssoRequestInfo.setOrderid(datajsonobj.getString("orderid"));
			ssoRequestInfo.setOrderidtype(BMDataContext.OrderIdType.TRANSTER.toString());
		}
		//校验md5签名
		if(!reqobj.getString("key").equals(RSATool.getMD5(reqobj.getString("agent")+reqobj.getString("timestamp")))) {
			return new RespEntity(RespCode.R1004);
		};
		try {
			PlayUser playuser=playUserRes.findByUsername(datajsonobj.getString("account"));
			if(playuser!=null) {
				  double goldcoins=playuser.getGoldcoins();
				  double availablecoins=aginfo.getAvailablecoins();
				  double money=new Double(datajsonobj.getString("money"));	
				  int transfertype=Integer.valueOf(datajsonobj.getString("transfertype")); // 0/1:转入/装出
				  switch(transfertype){ //type: 0/1  转入/转出
			         case 0 :
			        	 goldcoins=goldcoins+money;
			        	 availablecoins=availablecoins-money;
			        	 break;
			         case 1 :
			        	 goldcoins=goldcoins-money;
			        	 availablecoins=availablecoins+money;
			        	 break;
				   }
				  if(goldcoins<0){
					 return new RespEntity(RespCode.R1005);
				  }else {
					playuser.setGoldcoins(goldcoins);
					DisruptorHandler.published(playuser , playUserESRes , playUserRes);//加入队列更新缓存和DB
					PlayUserClient playUserClient=new PlayUserClient();
					BeanUtils.copyProperties(playUserClient , playuser);
					//更新缓存
					CacheHelper.getApiUserCacheBean().put(playUserClient.getId(),playUserClient, playUserClient.getOrgi());
					ssoCenterService.updateAgentCoins(aginfo, money, transfertype);
					ssoCenterService.saveTransferLog(request, playuser.getId(),  playuser.getUsername(),transfertype,money);//保存上下分日志
					SsoReqInfoESRes.save(ssoRequestInfo);
				  }
			}else {
				return new RespEntity(RespCode.R1006);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new RespEntity(RespCode.R9999);
		}
		return new RespEntity(RespCode.R0000);
	}
}